package com.xiaomo.gitee.datamanager.controller.user;

import com.xiaomo.gitee.datamanager.common.result.Code;
import com.xiaomo.gitee.datamanager.common.result.ImageWrapper;
import com.xiaomo.gitee.datamanager.common.result.Result;
import com.xiaomo.gitee.datamanager.dto.image.FilterImageDTO;
import com.xiaomo.gitee.datamanager.mapper.ImagedesMapper;
import com.xiaomo.gitee.datamanager.service.image.ImageService;
import com.xiaomo.gitee.datamanager.service.temp.PageService;
import com.xiaomo.gitee.datamanager.service.image.impl.ImageServiceImpl;
import com.xiaomo.gitee.datamanager.service.temp.PageServiceImpl;
import com.xiaomo.gitee.datamanager.util.HttpUtils;
import com.xiaomo.gitee.datamanager.util.JwtUtils;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.Executor;

@RestController
@RequestMapping("/api")
@Tag(name = "图片获取", description = "用户进行图片查询")
@RequiredArgsConstructor

public class UserImageController {

    private final ImageService imageService;
    private final PageService pageService;
    private final Executor threadPool;

    //@RequestMapping("/datas/image/{id}")
    @GetMapping("/image/{id}")
    @PreAuthorize("hasAuthority('image_info')")
    @Operation(
            summary = "获取原图",
            description = "获取图片的原图",
            security = @SecurityRequirement(name = JwtUtils.TOKEN_HEADER),
            parameters = {
                    @Parameter(
                            name = "id",
                            description = "图片ID,类型为UUID",
                            required = true,
                            in = ParameterIn.PATH
                    )
            },
            responses = {
                    @ApiResponse(
                            responseCode = Code.SUCCESS,
                            description = "返回图片",
                            content = @Content(
                                    mediaType = "image/jpg"
                            )
                    ),
                    @ApiResponse(
                            responseCode = "404",
                            description = "没有找到图片资源",
                            content = @Content(
                                    mediaType = "application/json",
                                    schema = @Schema(
                                            implementation = Result.class
                                    )
                            )
                    )
            }
    )
    public ResponseEntity<byte[]> showImage(@PathVariable String id, HttpServletResponse response) {
        ResponseEntity<byte[]> entity = imageService.getOriginalImage(id);
        if (entity == null) {
            /*HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            response.setStatus(404);
            return ResponseEntity.status(HttpStatus.NOT_FOUND).header(headers.toString()).body("没有找到图片资源");*/
            HttpUtils.writeJson(response, Result.fail(404, "没有找到图片资源"));
            return null;
        } else {
            response.setStatus(Integer.parseInt(Code.SUCCESS));
            return entity;
        }
    }

    @GetMapping("/simage/{id}")
    @PreAuthorize("hasAuthority('image_info')")
    @Operation(
            summary = "获取缩略图",
            description = "获取图片的缩略图",
            security = @SecurityRequirement(name = JwtUtils.TOKEN_HEADER),
            parameters = {
                    @Parameter(
                            name = "id",
                            description = "图片ID,类型为UUID",
                            required = true,
                            in = ParameterIn.PATH
                    )
            },
            responses = {
                    @ApiResponse(
                            responseCode = Code.SUCCESS,
                            description = "返回图片",
                            content = @Content(
                                    mediaType = "image/jpg"
                            )
                    ),
                    @ApiResponse(
                            responseCode = "404",
                            description = "返回响应数据模型",
                            content = @Content(
                                    mediaType = "application/json",
                                    schema = @Schema(
                                            implementation = Result.class
                                    )
                            )
                    )
            }
    )
    public ResponseEntity<byte[]> showSmallImage(@PathVariable String id, HttpServletResponse response) {
        ResponseEntity<byte[]> entity = imageService.getSmallImage(id);
        if (entity == null) {
            /*HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            return ResponseEntity.status(HttpStatus.NOT_FOUND).header(headers.toString()).body("没有找到图片资源");*/
            HttpUtils.writeJson(response, Result.fail(404, "没有找到图片资源"));
            return null;
        } else {
            return entity;
        }
    }

    @GetMapping("/search-image")
    @PreAuthorize("hasAuthority('image_info')")
    @Operation(
            summary = "搜索图片",
            description = "传递搜索信息和页码模糊查询图片，返回分页的图片封装模型列表",
            security = @SecurityRequirement(name = JwtUtils.TOKEN_HEADER),
            parameters = {
                    @Parameter(
                            name = "searchInfo",
                            description = "搜索信息",
                            required = true,
                            in = ParameterIn.QUERY
                    ),
                    @Parameter(
                            name = "page",
                            description = "页码",
                            required = true,
                            in = ParameterIn.QUERY
                    ),
                    @Parameter(
                            name = "amountPerPage",
                            description = "每页图片数量",
                            required = true,
                            in = ParameterIn.QUERY
                    )
            },
            responses = {
                    @ApiResponse(
                            responseCode = Code.SUCCESS,
                            description = "响应数据模型,data为Map,Map的value为封装图片模型(见Schema)",
                            content = @Content(
                                    mediaType = "application/json",
                                    schema = @Schema(
                                            anyOf = {Result.class, Map.class, ImageWrapper.class}
                                    )
                            )
                    ),
                    @ApiResponse(
                            responseCode = "500",
                            description = "获取失败,返回响应数据模型",
                            content = @Content(
                                    mediaType = "application/json",
                                    schema = @Schema(
                                            implementation = Result.class
                                    )
                            )
                    )
            }
    )
    public Result<?> searchImages(@RequestParam String searchInfo, @RequestParam int page, @RequestParam int amountPerPage) {
        return Result.ok(imageService.searchImagesService(searchInfo, page, amountPerPage));
    }

    /**
     * @param category 子类别id
     * @param page     页数
     * @return 图片json数据
     */
    @GetMapping("/images")
    @PreAuthorize("hasAuthority('image_info')")
    @Operation(
            summary = "获取数据集图片",
            description = "通过数据集id和页码获取分页后的图片封装模型列表",
            security = @SecurityRequirement(name = JwtUtils.TOKEN_HEADER),
            parameters = {
                    @Parameter(
                            name = "category",
                            description = "数据集ID",
                            required = true,
                            in = ParameterIn.QUERY
                    ),
                    @Parameter(
                            name = "page",
                            description = "页码",
                            required = true,
                            in = ParameterIn.QUERY
                    ),
                    @Parameter(
                            name = "amountPerPage",
                            description = "每页图片数量",
                            required = true
                    )
            },
            responses = {
                    @ApiResponse(
                            responseCode = Code.SUCCESS,
                            description = "响应数据模型,data为Map,Map的value为封装图片模型(见Schema)",
                            content = @Content(
                                    mediaType = "application/json",
                                    schema = @Schema(
                                            anyOf = {Result.class, Map.class, ImageWrapper.class}
                                    )
                            )
                    ),
                    @ApiResponse(
                            responseCode = "500",
                            description = "获取失败,返回响应数据模型",
                            content = @Content(
                                    mediaType = "application/json",
                                    schema = @Schema(
                                            implementation = Result.class
                                    )
                            )
                    )
            }
    )
    public Result<?> getClassifiedImages(@RequestParam Long category, @RequestParam int page, @RequestParam int amountPerPage) {
        /*String category = (String) request.get("category");
        int page = (int) request.get("page");*/
        return Result.ok(imageService.getClassifiedImagesService(category, page, amountPerPage));
    }

    /**
     * @return CustomImages
     */
    @PostMapping("/filter-image")
    @PreAuthorize("hasAuthority('image_info')")
    @Operation(
            summary = "筛选图片",
            description = "通过标签信息和页码筛选图片，返回分页的图片封装模型列表",
            security = @SecurityRequirement(name = JwtUtils.TOKEN_HEADER),
            parameters = {
                    @Parameter(
                            name = "data",
                            description = "传递图片筛选数据传输模型",
                            required = true,
                            schema = @Schema(
                                    implementation = FilterImageDTO.class
                            )
                    )
            },
            responses = {
                    @ApiResponse(
                            responseCode = Code.SUCCESS,
                            description = "响应数据模型,data为Map,Map的value为封装图片模型(见Schema)",
                            content = @Content(
                                    mediaType = "application/json",
                                    schema = @Schema(
                                            anyOf = {Result.class, Map.class, ImageWrapper.class}
                                    )
                            )
                    ),
                    @ApiResponse(
                            responseCode = Code.CLIENT_FAILED,
                            description = "筛选标签列表长度为0",
                            content = @Content(
                                    mediaType = "application/json",
                                    schema = @Schema(
                                            implementation = Result.class
                                    )
                            )
                    ),
                    @ApiResponse(
                            responseCode = Code.UNKNOWN_ERROR,
                            description = "获取失败,返回响应数据模型",
                            content = @Content(
                                    mediaType = "application/json",
                                    schema = @Schema(
                                            implementation = Result.class
                                    )
                            )
                    )
            }
    )
    public Result<?> filterImages(@RequestBody FilterImageDTO data) {
        if (data.getTagsId() != null && !data.getTagsId().isEmpty()) {
            return Result.ok(imageService.filterImages(data.getTagsId(), data.getPage(), data.getAmountPerPage()));
        }
        return Result.fail(Integer.parseInt(Code.CLIENT_FAILED),"请选择筛选标签");
    }

    @GetMapping("/info-image")
    @PreAuthorize("hasAuthority('image_info')")
    @Operation(
            summary = "获取图片描述",
            security = @SecurityRequirement(name = JwtUtils.TOKEN_HEADER),
            parameters = {
                    @Parameter(
                            name = "id",
                            description = "图片ID",
                            required = true
                    )
            },
            responses = {
                    @ApiResponse(
                            responseCode = Code.SUCCESS,
                            description = "获取成功",
                            content = @Content(
                                    mediaType = "application/json",
                                    schema = @Schema(
                                            implementation = Result.class
                                    )
                            )
                    )
            }
    )
    public Result<String> getDescription(String id) {
        return Result.ok(imageService.getDescription(id));
    }

}
